<template>
	<view style="min-height:100vh;background:#fff !important">
		<view class="auth" style="z-index:10">
			<!-- <view class="wanl-title">请输入账号</view> -->

			<view class="authtitle">登录发现更多精彩</view>

			<view class="logowrapper">
				<image class="logo" src="@/static/images/logo.png"></image>
				<view class="desc">一键触达本地脉络</view>
			</view>

			<form @submit="formSubmit">
				<!-- <view class="auth-group radius-bock bg-gray wlian-grey-light">
					<input placeholder="请输入手机号 / 用户名" placeholder-class="placeholder" name="account" type="text" maxlength="16"
					 confirm-type="next" @input="onKeyInput"></input>
				</view> -->
				<view class="auth-button flex flex-direction">
					<!-- <button form-type="submit" class="cu-btn sl radius-bock bg-orange" :disabled="submitDisabled">下一步</button> -->
					<!-- #ifdef MP-WEIXIN -->
					<!-- <view class="wanl-weixin-btn-info margin-tb-bj text-center text-sm">或</view> -->
<!-- 					<button type="primary" style="background-color:#ff7a3b" class="cu-btn sl radius-bock bg-no"
						open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">一键登录</button> -->
						<button type="primary" style="background-color:#ff7a3b" class="cu-btn sl radius-bock bg-no"
							open-type="getUserInfo" @getuserinfo="tologin({id:'weixin',name:'wlIcon-WeChat',platform:'mp_weixin'})">一键登录</button>
							
							<button @click="gotoback()" type="default" class="cu-btn sl radius-bock bg-no" style="margin-top:20rpx;background:#eee">继续逛逛</button>
					<!-- #endif -->
				</view>
				<!-- 同意服务条款 -->
				<checkbox-group :class="checked == 1 ? 'shake-horizontal' : ''" class="auth-clause"
					@change="CheckboxChange">
					<checkbox class="orange" :class="checked == 2 ? 'checked' : ''"
						:checked="checked == 2 ? true : false" value="2" />
					<view>
						我已阅读<text
							@tap="onDetails($store.state.common.appConfig.user_agreement, '用户协议')">用户协议</text>及<text
							@tap="onDetails($store.state.common.appConfig.privacy_protection, '隐私保护')">隐私权保护声明</text>
					</view>
				</checkbox-group>
			</form>
		</view>
		<view class="auth-foot" style="z-index:10">
			<view class="oauth">
				<!-- <view :class="item.name" class="cu-avatar lg round bg-white" v-for="(item, key) in providerList" @tap="tologin(item)" :key="key" ></view> -->
			</view>
			<view class="menu text-grey" style="z-index:-1000">
				<!-- <text @tap="register">注册</text> -->
				<text @tap="help">帮助</text>
			</view>
		</view>

		<uni-popup ref="popup1" type="bottom" border-radius="10px 10px 0 0">
			<view class="userinfowrapper">
				<view class="userinfotitle">
					<view class="userinfologo">
						<image src="@/static/images/logo.png"></image>
					</view>
					<view class="userinfotitlein">人人聚 申请</view>
				</view>

				<view class="desc">
					<view class="desctop">获取您的昵称、头像</view>
					<view class="descbot">提供具有辨识度的用户中心界面</view>
				</view>

				<view class="userinfocontent">
					<view class="item">
						<view class="name">头像</view>
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image class="avatar" :src="avatarUrl"></image>
						</button>
					</view>
					<view class="item" style="border-top:1rpx solid #eee">
						<view class="name">昵称</view>
						<input type="nickname" v-model="nickname" class="weui-input" placeholder="请输入昵称" />
					</view>
				</view>


				<view class="btnwrapper">
					<button type="primary" @click="saveuserinfo">保存</button>
				</view>

				<!--        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">-->
				<!--          <image class="avatar" src="{{avatarUrl}}"></image>-->
				<!--        </button>-->

			</view>
		</uni-popup>
	
				<uni-popup ref="phonepop">
		            <view class="phoneshow">
						<image src="../../../static/images/Frame.png"></image>
						<view class="title1">获取手机号</view>
						<view class="title">为了用户更好的可辨识度,小程序需要获取您的手机号</view>
		                <button type="primary" style="background-color:#ff7a3b;margin-top:20rpx;width:380rpx;" class="cu-btn sl radius-bock bg-no"
		                						open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">确认</button>
		            </view>
				</uni-popup>
	
	</view>
</template>
<script>
	import graceChecker from '@/common/graceChecker';
	import config from "@/common/config/config.js";
	const defaultAvatarUrl =
		'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'


	export default {
		data() {
			return {
				avatarUrl: defaultAvatarUrl,
				nickname: "",
				submitDisabled: true,
				providerList: [],
				loginRes: {},
				pageroute: '',
				checked: [],
				
				currentToken:"",
				currentProvider:"",
			};
		},
		async onLoad(option) {
			// #ifdef H5
			// 微信内置浏览器登录
			if (this.$jssdk.isWechat()) {
				let local = window.location.href; // 获取页面url
				let code = this.getUrlCode().code; // 截取code
				// 获取之前的code
				let oldCode = uni.getStorageSync('wanlshop:code');
				// 如果没有code，就去请求获取code
				if (code == null || code === '' || code == 'undefined' || code == oldCode) {
					let uri = encodeURIComponent(local);
					let page = this.$wanlshop.prePage().$mp.page;
					uni.setStorageSync('wanlshop:code', 0); // 设置旧的code为0，避免死循环
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.$wanlshop.config('appid')}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=${encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`)}#wechat_redirect`
				} else {
					let pageroute = this.getUrlCode().state; // 截取state
					uni.setStorageSync('wanlshop:code', code); // 保存最新code
					await uni.request({
						url: '/wanlshop/user/third',
						method: 'POST',
						data: {
							platform: 'h5_weixin',
							code: code,
							client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
								"wanlshop:chat_client_id") : null
						},
						success: res => {
							this.$store.dispatch('user/login', res.data);
							this.$store.dispatch('cart/login');
							this.$store.dispatch('chat/get');
							uni.reLaunch({
								url: decodeURIComponent(pageroute)
							});
						}
					});
				}
			} else {
				let page = this.$wanlshop.prePage().$mp.page;
				this.pageroute = encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`);
			}
			// 未来版本开发
			// this.providerList = [{
			// 	name: 'wlIcon-QQ',
			// 	platform: 'web_qq'
			// }];
			// #endif

			// 获取第三方登录
			// #ifndef H5
			let page = this.$wanlshop.prePage().$mp.page;
			this.pageroute = encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`);
			uni.getProvider({
				service: 'oauth',
				success: (res) => {
					this.providerList = res.provider.map((value) => {
						let providerName = '';
						let platform = '';
						switch (value) {
							case 'weixin':
								providerName = 'wlIcon-WeChat';
								// #ifdef MP
								platform = 'mp_weixin';
								// #endif
								// #ifdef APP-PLUS
								platform = 'app_weixin';
								// #endif
								break;
							case 'qq':
								providerName = 'wlIcon-QQ'
								// #ifdef MP
								platform = 'mp_qq';
								// #endif
								// #ifdef APP-PLUS
								platform = 'app_qq';
								// #endif
								break;
							case 'sinaweibo':
								providerName = 'wlIcon-WeiBo'
								platform = 'app_weibo';
								break;
							case 'xiaomi':
								providerName = 'wlIcon-Xiaomi'
								platform = 'app_xiaomi';
								break;
							case 'apple':
								providerName = 'wlIcon-Apple'
								platform = 'apple';
								break;
						}
						
						
						return {
							id: value,
							name: providerName,
							platform: platform
						}
					});
				},
				fail: (error) => {
					console.log('获取登录通道失败', error);
				}
			});
			// #endif

			// 防止刷新登录态，uni.login code提前获取
			// #ifdef MP-WEIXIN
			uni.login({
				provider: 'weixin',
				success: res => {
					this.loginRes = res;
				},
				fail: err => {
					this.$wanlshop.msg(err.msg);
				}
			});
			// #endif
		},
		methods: {
			
			gotoback(){
				uni.reLaunch({
					url:"/pages/local"
				})
			},

			onChooseAvatar(e) {
				this.avatarUrl = e.detail.avatarUrl;
				this.uploadFile(this.avatarUrl);
			},


			async uploadFile(file) {
				let that = this;
				await uni.uploadFile({
				    url: '/wanlshop/common/upload',
				    filePath: file,
				    name: 'file',
				    success: data => {
						that.avatarUrl = config.cdnurl + JSON.parse(data.data).data.url;				
					}
				});
			},

			saveuserinfo() {
				//提交保存用户头像
				if (!this.avatarUrl || !this.nickname) {
					uni.showToast({
						title: "请选择头像和昵称",
						icon: "none"
					})
					return false;
				}
				let that = this;
				
				//上传用户头像
				
				uni.request({
					url: '/wanlshop/user/profile',
					method: 'POST',
					data: {
						avatar: this.avatarUrl,
						nickname: this.nickname,
						currentToken:this.currentToken,
					},
					success(res) {
						if (res.res.code == 1) {
							uni.reLaunch({
								url: decodeURIComponent(that.pageroute)
							});
						} else {
							uni.showToast({
								title: "网络错误请重试"
							})
						}
					}
				});

			},



			CheckboxChange(e) {
				console.log(e.detail.value)
				this.checked = e.detail.value;
			},
			// 第三方登录
			tologin(provider) {
				console.log(this.checked)
				if(this.checked.length == 0){
					this.$wanlshop.msg("请勾选已阅读用户协议与声明")
					return false;
				}
				
				
				uni.showLoading({
					title: '登录中'
				});
				// #ifndef H5   
				//如果不是H5 ， 这里就是我们小程序的登录
				
				
				//查看下，store中的 upuserid 的值，并且传入
				console.log(this.$store.state);
				
				let upuserid = this.$store.getters['user/getUpuserid'];
				console.log(upuserid);
				let district = this.$store.state.common.addressData.address.district?this.$store.state.common.addressData.address.district:"";
				uni.login({
					provider: provider.id,
					// #ifdef MP-ALIPAY
					scopes: 'auth_user', //支付宝小程序需设置授权类型
					// #endif
					success: (loginRes) => {
					
						uni.request({
							url: '/wanlshop/user/third',
							method: 'POST',
							data: {
								platform: provider.platform,
								loginData: loginRes,
								upuserid,
								district,
								client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni
									.getStorageSync("wanlshop:chat_client_id") : null
							},
							success: res => {
								uni.hideLoading();
								if (res.data.binding == 0) {
									// #ifdef MP-WEIXIN
										//如果是微信， 弹出获取电话号的框， 
										this.$refs.phonepop.open();
										this.currentToken = res.data.token;
										this.currentProvider = provider;
									
									// #endif
									// #ifndef MP-WEIXIN
										this.$wanlshop.to(
											`/pages/user/auth/perfect?token=${res.data.token}&platform=${provider.platform}&url=${this.pageroute}`
										);
									// #endif
									
								} else {
									this.$store.dispatch('user/login', res.data);
									this.$store.dispatch('cart/login');
									this.$store.dispatch('chat/get');
									// #ifdef MP-WEIXIN
									
									uni.reLaunch({
										url: decodeURIComponent(this.pageroute)
									});
									
									// #endif
									// #ifndef MP-WEIXIN
										uni.reLaunch({
											url: decodeURIComponent(this.pageroute)
										});
									// #endif
									
								}
							}
						});
						// 隐藏键盘
						uni.hideKeyboard();
					},
					fail: err => {
						this.$wanlshop.msg(err.msg);
					}
				});
				// #endif
				// #ifdef H5
				uni.request({
					url: '/wanlshop/user/third_web',
					method: 'POST',
					data: {
						platform: provider.platform,
						client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
							"wanlshop:chat_client_id") : null
					},
					success: res => {
						uni.hideLoading();
						this.$store.dispatch('user/login', res.data);
						this.$store.dispatch('cart/login');
						this.$store.dispatch('chat/get');
						// 返回页面
						uni.reLaunch({
							url: decodeURIComponent(this.pageroute)
						});
					}
				});
				// #endif
			},
			onKeyInput(e) {
				this.submitDisabled = false
			},
			// 号码登录，暂时支持微信小程序，后续版本逐渐开发
			async decryptPhoneNumber(e) {
				if (e.detail.errMsg != "getPhoneNumber:fail user deny") {
					await uni.request({
						url: '/wanlshop/user/phone',
						method: 'POST',
						data: {
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv,
							code: this.loginRes.code,
							client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
								"wanlshop:chat_client_id") : null
						},
						success: res => {
							this.$refs.phonepop.close();
							this.$store.dispatch('user/login', res.data);
							this.$store.dispatch('cart/login');
							// 返回页面
							//uni.reLaunch({url: decodeURIComponent(this.pageroute)});
							if (res.res.code == 1) {
								if (res.res.data.userinfo.avatar.startsWith('data') || !res.res.data
									.userinfo.nickname) {
									this.$refs.popup1.open();
								} else {
									uni.reLaunch({
										url: decodeURIComponent(this.pageroute)
									});
								}
							} else {
								uni.showToast({
									title: "网络错误请重试"
								})
							}




						}
					});
				}
			},
			// 账户登录
			formSubmit(e) {
				if (this.checked == 2) {
					//将下列代码加入到对应的检查位置
					//定义表单规则
					let rule = [{
						name: 'account',
						checkType: 'phoneno',
						errorMsg: '不是手机号码'
					}];
					//进行表单检查
					let formData = e.detail.value;
					let checkRes = graceChecker.check(formData, rule);
					// ..检查是否注册-没注册跳转注册
					if (checkRes) {
						uni.request({
							url: '/wanlshop/validate/check_mobile_exist',
							data: {
								mobile: formData.account
							},
							// 1.1.8升级
							complete: res => {
								if (res.res.code == 0) {
									uni.showModal({
										title: '提示',
										content: '账号不存在，是否注册？',
										confirmText: '取消',
										cancelText: '确定',
										success: (res) => {
											if (res.confirm) {
												console.log('取消');
											} else if (res.cancel) {
												this.$wanlshop.to(
													`register?mobile=${formData.account}&url=${this.pageroute}`
													);
											}
										}
									});
								} else {
									this.$wanlshop.to(`phone?mobile=${formData.account}&url=${this.pageroute}`,
										'none');
								}
							}
						});
					} else {
						if (formData.account) {
							this.$wanlshop.to(`name?name=${formData.account}&url=${this.pageroute}`, 'none');
						} else {
							this.$wanlshop.msg('请填写账号');
						}
					}
				} else {
					this.checked = 1;
					setTimeout(() => {
						this.checked = 0;
						this.$wanlshop.msg('请先同意用户协议和隐私保护声明');
						this.checked = ['2'];
					}, 300)
				}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				// this.winUrl = url;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			},
			register() {
				this.$wanlshop.to(`register?url=${this.pageroute}`);
			},
			help() {
				this.$wanlshop.to(`/pages/user/help?url=${this.pageroute}`);
			}
		}
	};
</script>

<style scoped lang="scss">
	@import url("auth.css");

	.userinfowrapper {
		z-index: 1000;
		width: 100%;
		padding: 30rpx 50rpx;
		box-sizing: border-box;
		background: #fff;

		.userinfotitle {
			width: 100%;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.userinfologo {
				margin-right: 20rpx;

				image {
					width: 54rpx;
					height: 54rpx;
				}
			}

			.userinfotitlein {
				color: #000;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.desc {
			margin: 40rpx 0;

			.desctop {
				font-size: 36rpx;
				color: #000;
				font-weight: bold;
			}

			.descbot {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: #868686;
			}
		}


		.userinfocontent {
			padding: 15rpx 0;
			border-top: 1rpx solid #eee;
			border-bottom: 1rpx solid #eee;
			margin-bottom: 40rpx;

			.item {
				padding: 0 20rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				height: 100rpx;

				.avatar-wrapper {
					width: 60rpx;
					height: 60rpx;
					padding: 0;
					transform: translate(-350%, 0rpx);

					image {
						width: 60rpx;
						height: 60rpx;
					}
				}

				.name {
					flex-basis: 100rpx;
					font-weight: bold;
					font-size: 28rpx;
				}
			}
		}

		.btnwrapper {
			width: 50%;
			margin: 0 auto;
			height: 180rpx;
		}
	}
</style>